from flask import g
from flask import request, jsonify
from flask import session

from info import constants
from info.models import User, News, Category
from info.response_code import RET
from info.utils.commons import user_login_data
from . import index_blue
from info import redis_store
from flask import render_template, current_app

# 分类展示新闻
# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid（哪个分类）,page（第几页）,per_page（每页几条数据）
# 返回值: data数据
@index_blue.route('/newslist')
def newslist():
    # 获取参数
    cid = request.args.get("cid", 1)
    page = request.args.get("page", 1)
    per_page = request.args.get("per_page", 10)
    # 转变参数类型
    page = int(page)
    per_page = int(per_page)
    # 分页查询
    # 由于如果cid=1，数据库中无数据，所以要加入判断
    filter_condition = ""
    if cid != "1":
        filter_condition = (News.category_id == cid)
    paginate = News.query.filter(filter_condition).order_by(News.create_time.desc()).paginate(page, per_page, False)

    # - 4.获取分页对象属性,总页数,当前页,当前页对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 5. 对象列表转成字典列表
    news_list = []
    for item in items:
        news_list.append(item.to_dict())

    # - 6.拼接数据,返回响应
    return jsonify(errno=RET.OK, errmsg="获取成功", totalPage=totalPage, currentPage=currentPage, newsList=news_list)



@index_blue.route('/')
@user_login_data
def index():
    # 检测用户是否处于登陆状态
    # user_id = session.get("user_id")
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 首页显示热搜排行
    # 1： 按搜索亮获取10条信息
    try:
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
    # 2: 遍历新闻
    click_new_list = []
    for item in news:
        click_new_list.append(item.to_dict())

    # 首页分类恩健
    # 找到所有分类
    try:
        categoris = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    # 遍历所有分类
    categoris_list = []
    for item in categoris:
        categoris_list.append(item.to_dict())

    # 携带数据渲染页面
    data = {
        "user_info": g.user.to_dict() if g.user else  "",
        "click_new_list": click_new_list,
        "categoris": categoris_list,
    }

    return render_template("news/index.html", data = data)




@index_blue.route("/favicon.ico")
def gei_web_logo():
    return current_app.send_static_file("news/favicon.ico")
